package com.tc.zigbee.mt;

import java.io.IOException;
import java.util.LinkedList;
import java.util.List;

import com.tc.gateway.ErrorListener;
import com.tc.gateway.tunnel.TunnelOutput;
import com.tc.serial.SerialStream;
import com.tc.zigbee.mt.income.IncomeMessage;


public class Monitor implements ErrorListener{
	List<MessageListener> listeners = new LinkedList<MessageListener>();
	Thread sendThread;
	IncomingMessageReader receivThread;
	SerialStream stream;
	ErrorListener errorListener;
	public void addListener(MessageListener l){
		listeners.add(l);
	}
	public Monitor(SerialStream stream, TunnelOutput ts){
		this.stream = stream;
		if(stream == null)
			return;
		receivThread = new IncomingMessageReader(stream, new MessageListener(){

			public void onMessage(IncomeMessage msg) {
				for(MessageListener l : listeners)
					l.onMessage(msg);
			}
			
		},
		ts);
		receivThread.setErrorListener(this);
		sendThread = new Thread("sendThread"){
			@Override
			public void run() {
				while(true){
					MtCommand mc = RequestQueue.poll();
					try {
					if(mc != null)
						sendRequest(mc);

						Thread.sleep(300);
					} catch (Exception e) {
						e.printStackTrace();
						Monitor.this.receivThread.interrupt();
						if(errorListener != null)
							errorListener.onException(e);
						return;
					}
				}
			}
		};
	}

public void start(){
	if(stream == null)
		return;
	this.receivThread.start();
	this.sendThread.start();
}

	void sendRequest(MtCommand req) throws IOException{
		if(stream == null)
			return;
			byte[] rf = req.frame;
			stream.getOutputStream().write(rf);
			stream.getOutputStream().flush();
			
	
	}

	public void setErrorListener(ErrorListener errorListener) {
		this.errorListener = errorListener;
	}
	static public void main(String[] s){
	
//		Monitor m = new Monitor();
//		ZigbeeManager zm = new ZigbeeManager();
//		m.addListener(zm);
//	
//		m.start();
//		MtCommand r = RequestFactory.MtIEEEAddrRequest((short)0x00, (byte)0, (byte)1);
//		RequestQueue.commandqueue.offer(r);
	}
	public void onException(Throwable e) {
		this.sendThread.interrupt();
		this.errorListener.onException(e);
		
		
	}

}
